package com.kingsystem.kingteachermarks_backend.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kingsystem.kingteachermarks_backend.KingUtil.JwtOper;
import com.kingsystem.kingteachermarks_backend.entity.Dept;
import com.kingsystem.kingteachermarks_backend.entity.SystemUser;
import com.kingsystem.kingteachermarks_backend.mapper.SystemUserMapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author leiyue_yao
 * @since 2025-05-22
 */
@Controller
@RequestMapping("/systemUser")
@CrossOrigin
public class SystemUserController {

    @Autowired
    private SystemUserMapper su;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/setRedis")
    @ResponseBody
    public String setRedis() {
        List<SystemUser> li = new ArrayList<>();
        for (int i = 0; i < 70; i++) {
            SystemUser suObj = new SystemUser();
            suObj.setTableKey("redis_" + i);
            suObj.setRealName("张三_" + i);
            suObj.setUserName("admin_" + i);
            suObj.setTitle("教授_" + i);
            li.add(suObj);
        }
        String jsonStr = JSON.toJSONString(li);
        stringRedisTemplate.opsForValue().set("users", jsonStr);

        String returnStr = "";

        long t_start3 = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            stringRedisTemplate.opsForValue().set("users", jsonStr);
        }
        long t_end3 = System.currentTimeMillis();
        long totalTime3 = t_end3 - t_start3;
        returnStr += "redis写100次执行时间：" + totalTime3 + "ms----";

        String aa="";
        long t_start = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            aa = stringRedisTemplate.opsForValue().get("users");
        }
        long t_end = System.currentTimeMillis();
        long totalTime = t_end - t_start;
        returnStr += "redis总共执行时间：" + totalTime + "ms----";


        long t_start2 = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            su.selectList(null);
        }
        long t_end2 = System.currentTimeMillis();
        long totalTime2 = t_end2 - t_start2;
        returnStr += "mybatis总共执行时间：" + totalTime2 + "ms";

        return aa;
    }

    @PostMapping("/getSingleUser")
    @ResponseBody
    @ApiOperation(value = "获取单个用户", notes = "根据用户名和密码获取单个用户信息")
    public SystemUser getSingleUser(@RequestParam("user_name") String user_name
            , @RequestParam("psw") String psw) {
        QueryWrapper<SystemUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", user_name)
                .eq("psw", psw);

        String JwtStr = JwtOper.generateToken(user_name);

        String name = JwtOper.parseToken(JwtStr).get("username", String.class);
        Date expirationDate = JwtOper.parseToken(JwtStr).getExpiration();
        Boolean isExpired = JwtOper.isTokenExpired(JwtStr);

        SystemUser user = su.selectOne(wrapper);
        return user;
    }


    @RequestMapping("/getAllUsers")
    @ResponseBody
    @ApiOperation(value = "获取所有用户", notes = "获取所有用户，一般是选择用户不分权限范围限制时，使用该接口")
    public List<SystemUser> getAllUsers() {
        QueryWrapper<SystemUser> qw = new QueryWrapper<>();
        qw.select("TableKey",
                        "dept_id",
                        "user_name",
                        "real_name",
                        "title",
                        "eud_history",
                        "diploma",
                        "birth",
                        "face_img")
                .eq("flag_del", 0);
        List<SystemUser> li = su.selectList(qw);
        return li;
    }

    @PostMapping("/getUsersByDeptId")
    @ResponseBody
    public List<SystemUser> getUsersByDeptId(
            @RequestParam(required = false) String deptId,
            @RequestParam(required = false) String realName) {

        QueryWrapper<SystemUser> qw = new QueryWrapper<>();

        if (deptId != null && !deptId.isEmpty()) {
            qw.eq("dept_id", deptId);
        }

        if (realName != null && !realName.isEmpty()) {
            qw.like("real_name", realName);
        }

        return su.selectList(qw);
    }

    @PostMapping("/edituser")
    @ResponseBody
    public String editDept(@RequestBody SystemUser user) {
        try {
            System.out.println(user);
            su.updateById(user);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }

    @PostMapping("/delDeptById")
    @ResponseBody
    public String delDeptById(@RequestBody SystemUser user) {
        try {
            QueryWrapper<SystemUser> qw = new QueryWrapper<>();
            qw.eq("tableKey", user.getTableKey());
            su.delete(qw);
            return "success";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @CrossOrigin
    @RequestMapping("/adduser")
    @ResponseBody
    public String adduser(@RequestBody SystemUser user) {
        try {
            su.insert(user);
            return "success";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @CrossOrigin
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestBody SystemUser user) {
        try {
            su.insert(user);
            return "success";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

}
